import { createSlice } from '@reduxjs/toolkit'
import request from '../../utils/request'
import { getStorage, removeStorage, setStorage } from '../../utils/localStorage'
import { loginService, getUserInfoService } from '@/apis/user'

const userStore = createSlice({
  name: 'user',
  initialState: {
    // 先从本地存储获取
    token: getStorage('token') || '',
    userInfo: {}
  },
  reducers: {
    // 同步修改方法
    setToken(state, action) {
      state.token = action.payload
      // 登录成功后，将token存储到本地
      setStorage('token', state.token)
    },
    setUserInfo(state, action) {
      state.userInfo = action.payload
    },
    // 退出登录
    logOut(state) {
      state.token = ''
      state.userInfo = {}
      // 退出登录后，将本地存储清空
      removeStorage('token')
    }
  }
})

// 解构出 actionCreator
const { setToken, setUserInfo, logOut } = userStore.actions

// 异步action封装
const fetchLogin = (loginForm) => {
  return async (dispatch) => {
    try {
      const res = await loginService(loginForm)
      dispatch(setToken(res.data.token))
      return res.data.token
    } catch (error) {
      console.log(error)
    }
  }
}

const getUserInfo = () => {
  return async (dispatch) => {
    try {
      const res = await getUserInfoService()
      dispatch(setUserInfo(res.data))
    } catch (error) {
      console.log(error)
    }
  }
}
// 获取 reducer 函数
const userReducer = userStore.reducer

export { fetchLogin, getUserInfo, logOut }

export default userReducer
